package com.example.demo.config;

import com.example.demo.entity.CrawlerTask;
import com.example.demo.job.CrawlerJob;
import com.example.demo.mapper.CrawlerTaskMapper;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.util.List;

@Configuration
public class QuartzConfig {

    @Autowired
    private CrawlerTaskMapper crawlerTaskMapper;

    @Autowired
    private Scheduler scheduler;

    @EventListener(ContextRefreshedEvent.class)
    public void initializeJobsAfterContextRefreshed() throws SchedulerException {
        // 清除所有已存在的任务
        scheduler.clear();

        // 从数据库中获取任务列表
        List<CrawlerTask> tasks = crawlerTaskMapper.selectList();
        for (CrawlerTask task : tasks) {
            System.out.println(task);
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("taskName", task.getTaskName());

            JobDetail job = JobBuilder.newJob(CrawlerJob.class)
                    .withIdentity(task.getTaskName())
                    .usingJobData(jobDataMap)
                    .build();

            Trigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(task.getTaskName() + "Trigger")
                    .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression()))
                    .build();

            scheduler.scheduleJob(job, cronTrigger);
        }
    }

    @Bean
    public Scheduler scheduler() throws SchedulerException {
        SchedulerFactory schedulerFactory = new org.quartz.impl.StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.start();
        return scheduler;
    }
}
